#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define DATALEN 100

// 函数声明
void caesarEncryptChar(char plaintext, char *ciphertext, int key);
void caesarDecryptChar(char ciphertext, char *plaintext, int key);
void caesarEncryptText(const char plaintext[], char ciphertext[], int key);
void caesarDecryptText(const char ciphertext[], char plaintext[], int key);

int main() {
    const char originalText[] = "Hello, World!"; // 原始文本（明文）
    char encryptedText[DATALEN ];                     // 加密后的文本（密文）
    char decryptedText[DATALEN];                     // 解密后的文本（明文）
    int key = 3;                               // 位移量

    printf("Original text: %s\n", originalText);

    // 测试字符加密和解密
    char testChar = 'A';
    char encryptedChar, decryptedChar;
    
    caesarEncryptChar(testChar, &encryptedChar, key);
    caesarDecryptChar(encryptedChar, &decryptedChar, key);

    printf("Normal Original char: %c, Encrypted char: %c, Decrypted char: %c\n",
           testChar, encryptedChar, decryptedChar);

    testChar = 'Z';
    caesarEncryptChar(testChar, &encryptedChar, key);
    caesarDecryptChar(encryptedChar, &decryptedChar, key);

    printf("Boundary Original char: %c, Encrypted char: %c, Decrypted char: %c\n",
           testChar, encryptedChar, decryptedChar);

    testChar = '9';
    
    caesarEncryptChar(testChar, &encryptedChar, key);
    caesarDecryptChar(encryptedChar, &decryptedChar, key);

    printf("Exceptional Original char: %c, Encrypted char: %c, Decrypted char: %c\n",
           testChar, encryptedChar, decryptedChar);



    // 加密文本
    caesarEncryptText(originalText, encryptedText, key);
    printf("Encrypted text: %s\n", encryptedText);

    // 解密文本
    caesarDecryptText(encryptedText, decryptedText, key);
    printf("Decrypted text: %s\n", decryptedText);

    return 0;
}

// 单字符凯撒加密
void caesarEncryptChar(char plaintext, char *ciphertext, int key) {
    if (isalpha(plaintext)) {
        char base = islower(plaintext) ? 'a' : 'A';
        *ciphertext = (plaintext - base + key) % 26 + base;
    } else {
        *ciphertext = plaintext; // 非字母字符不变
    }
}

// 单字符凯撒解密
void caesarDecryptChar(char ciphertext, char *plaintext, int key) {
    if (isalpha(ciphertext)) {
        char base = islower(ciphertext) ? 'a' : 'A';
        *plaintext = (ciphertext - base - key + 26) % 26 + base;
    } else {
        *plaintext = ciphertext; // 非字母字符不变
    }
}

// 加密文本
void caesarEncryptText(const char plaintext[], char ciphertext[], int key) {
    for (int i = 0; plaintext[i] != '\0'; ++i) {
        caesarEncryptChar(plaintext[i], &ciphertext[i], key);
    }
    ciphertext[strlen(plaintext)] = '\0'; // 添加字符串结束符
}

// 解密文本
void caesarDecryptText(const char ciphertext[], char plaintext[], int key) {
    for (int i = 0; ciphertext[i] != '\0'; ++i) {
        caesarDecryptChar(ciphertext[i], &plaintext[i], key);
    }
    plaintext[strlen(ciphertext)] = '\0'; // 添加字符串结束符
}

